import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'logic.dart';

class OrderManagementPage extends StatelessWidget {
  final OrderManagementLogic logic = Get.put(OrderManagementLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('订单管理'),
        backgroundColor: Color(0xFFBE9650),
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: logic.loadOrders,
          ),
        ],
      ),
      body: Obx(() {
        if (logic.isLoading.value) {
          return Center(child: CircularProgressIndicator());
        }

        if (logic.orders.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.receipt_long, size: 64, color: Colors.grey),
                SizedBox(height: 16),
                Text('暂无订单', style: TextStyle(fontSize: 18, color: Colors.grey)),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: logic.loadOrders,
          child: ListView.builder(
            padding: EdgeInsets.all(16),
            itemCount: logic.orders.length,
            itemBuilder: (context, index) {
              final order = logic.orders[index];
              final isExpanded = logic.expandedOrderId.value == order.id;
              
              return Card(
                margin: EdgeInsets.only(bottom: 16),
                elevation: 2,
                child: Column(
                  children: [
                    // 订单头部信息
                    ListTile(
                      title: Row(
                        children: [
                          Text('订单 #${order.id}', 
                            style: TextStyle(fontWeight: FontWeight.bold)
                          ),
                          SizedBox(width: 8),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                            decoration: BoxDecoration(
                              color: logic.getStatusColor(order.status).withOpacity(0.2),
                              borderRadius: BorderRadius.circular(12),
                              border: Border.all(
                                color: logic.getStatusColor(order.status),
                                width: 1,
                              ),
                            ),
                            child: Text(
                              logic.getStatusText(order.status),
                              style: TextStyle(
                                color: logic.getStatusColor(order.status),
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ],
                      ),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 4),
                          Text('用户: ${order.username}'),
                          Text('时间: ${DateFormat('yyyy-MM-dd HH:mm').format(order.createdAt)}'),
                          Text('总价: ¥${order.totalPrice.toStringAsFixed(2)}', 
                            style: TextStyle(
                              color: logic.primaryColor,
                              fontWeight: FontWeight.bold,
                            )
                          ),
                        ],
                      ),
                      trailing: IconButton(
                        icon: Icon(
                          isExpanded ? Icons.expand_less : Icons.expand_more,
                          color: logic.primaryColor,
                        ),
                        onPressed: () => logic.toggleOrderExpanded(order.id),
                      ),
                    ),
                    
                    // 展开的订单详情
                    if (isExpanded) ...[
                      Divider(),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 16),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text('配送地址', 
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 16,
                              )
                            ),
                            SizedBox(height: 4),
                            Text('${order.address} ${order.addressDetail}'),
                            if (order.remark.isNotEmpty) ...[
                              SizedBox(height: 8),
                              Text('备注', 
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  fontSize: 16,
                                )
                              ),
                              SizedBox(height: 4),
                              Text(order.remark),
                            ],
                            SizedBox(height: 8),
                            Text('订单项目', 
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: 16,
                              )
                            ),
                            SizedBox(height: 8),
                            
                            // 订单项目列表
                            ...order.items.map((item) => Padding(
                              padding: EdgeInsets.only(bottom: 8),
                              child: Row(
                                children: [
                                  ClipRRect(
                                    borderRadius: BorderRadius.circular(4),
                                    child: Image.network(
                                      item.foodImage,
                                      width: 40,
                                      height: 40,
                                      fit: BoxFit.cover,
                                      errorBuilder: (context, error, stackTrace) {
                                        return Container(
                                          width: 40,
                                          height: 40,
                                          color: Colors.grey[300],
                                          child: Icon(Icons.broken_image, size: 20, color: Colors.grey[600]),
                                        );
                                      },
                                    ),
                                  ),
                                  SizedBox(width: 8),
                                  Expanded(
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(item.foodName),
                                        Text(
                                          '¥${item.price.toStringAsFixed(2)} × ${item.quantity}',
                                          style: TextStyle(color: Colors.grey[600], fontSize: 12),
                                        ),
                                      ],
                                    ),
                                  ),
                                  Text(
                                    '¥${(item.price * item.quantity).toStringAsFixed(2)}',
                                    style: TextStyle(fontWeight: FontWeight.bold),
                                  ),
                                ],
                              ),
                            )).toList(),
                            
                            Divider(),
                            
                            // 订单操作按钮
                            Padding(
                              padding: EdgeInsets.symmetric(vertical: 8),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  if (order.status != 'COMPLETED' && order.status != 'CANCELLED') ...[
                                    ElevatedButton(
                                      onPressed: () => logic.completeOrder(order),
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: Colors.green,
                                        foregroundColor: Colors.white,
                                      ),
                                      child: Text('完成订单'),
                                    ),
                                    SizedBox(width: 8),
                                  ],
                                  if (order.status == 'PAID') ...[
                                    ElevatedButton(
                                      onPressed: () => logic.updateOrderStatus(order, 'PREPARING'),
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: Colors.purple,
                                        foregroundColor: Colors.white,
                                      ),
                                      child: Text('开始准备'),
                                    ),
                                    SizedBox(width: 8),
                                  ],
                                  if (order.status == 'PREPARING') ...[
                                    ElevatedButton(
                                      onPressed: () => logic.updateOrderStatus(order, 'DELIVERING'),
                                      style: ElevatedButton.styleFrom(
                                        backgroundColor: Colors.indigo,
                                        foregroundColor: Colors.white,
                                      ),
                                      child: Text('开始配送'),
                                    ),
                                    SizedBox(width: 8),
                                  ],
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ],
                  ],
                ),
              );
            },
          ),
        );
      }),
    );
  }
}
